/** Class Name: OORTelesalesGetFirstLead
 * Author: Accenture
 * Date: 3-March-2011
 * Requirement/Project Name: OOR Telesales
 * Requirement Description: 
 **/
public class OORTelesalesGetFirstLead
{
    private final ApexPages.StandardController stdController;
    private final ApexPages.StandardSetController stdSetcontroller;

    public String finalURL{get;set;}
    public String errorMsg{get;set;}
    public String nextLeadId {get;set;}
    public String campId {get;set;}
    public ID localAdvertiserRecordTypeID = RecordTypeHelper.GetRecordTypeIdByDevName('Lead', OORTelesalesTextConstant.LOCAL_ADVERTISER_LEAD_REC_TYPE);  



   /**
    *  Constructor 
    *
    */
    public OORTelesalesGetFirstLead(ApexPages.StandardController controller) 
    {
        stdController =controller;
        String returnUrl = ApexPages.currentPage().getParameters().get('id');
        finalURL = returnUrl;
    }
  
   /**
    *  Constructor 
    *
    */
   public OORTelesalesGetFirstLead(ApexPages.StandardSetController ctrl) 
   {
      stdSetcontroller= ctrl;
      String returnUrl = ApexPages.currentPage().getParameters().get('retUrl');
      finalURL = returnUrl ; //URL.getSalesforceBaseUrl().toExternalForm(); 
   }
   
   /**
    * Get the first lead of associated Campagin action invokes form Campaign List view 
    *
    */   
   public void getFirstLead()
   { 
       List <ID> campList= new List<Id>();
       Campaign  campObj = null;
       nextLeadId = '';
       errorMsg = null;
      
       // Check If user has selected any record 
       if (stdSetcontroller.getSelected().size() <= 0 )
       {
           errorMsg = OORTelesalesTextConstant.SELECT_ONE_CAMPAIGN_ERR_MSG  ;  
           return;
       }
       // check if user has selected more more than one campaign 
       else if (stdSetcontroller.getSelected().size() > 1 )
       {
           errorMsg = OORTelesalesTextConstant.SELECT_ONLY_ONE_CAMPAIGN_ERR_MSG  ;  
           return;
       }       
       
       for(sObject  sObj :stdSetcontroller.getSelected())
       { 
        campObj = (Campaign)sObj;
        campList.add(campObj.ID);
       } 
       campId =  campList.get(0);
       fetchLead(campId);
   }
   
   /**
    * Get the first lead of associated Campagin action invoked form Campaign detail page  
    *
    */   
   public void getFirstLeadFromDetail( )
   {
        Campaign camp = (Campaign)stdController.getRecord();
        nextLeadId = '';
        errorMsg = null; 
       
        fetchLead(camp.id);
   }
   
   /**
    *  Fetch lead associated with the campaign 
    *
    */   
   private void fetchLead(String campID)
   {
       final Id OOR_TELE_CAMPAIGN_LEAD_QUEUE = OORTelesalesUtility.getQueueID(OORTelesalesTextConstant.OOR_TELE_CAMPAIGN_LEAD_QUEUE); 
       List <CampaignMember> campaignMembList  =null;
       List <Lead> leadList= null;
       Lead leadObj = null;
       
       try
       {
           /* get all the Campaign member and associated lead  which 
              is in lead status = NEW ,
              temp owner is false,
              owner is queue and 
              campaign timer is < now() or campaign timer is null */
            
           campaignMembList = [Select Id,LeadId ,Campaign.IsActive from CampaignMember Where  CampaignId=:campId   and LeadId!=null and LeadStatus__c='New' and Campaign.IsActive= true and lead.TemporaryOwner__c = false and lead.RecordTypeId=:localAdvertiserRecordTypeID and lead.ownerid = :OOR_TELE_CAMPAIGN_LEAD_QUEUE  and ( lead.CampaignTimer__c = null or lead.CampaignTimer__c < :System.Now())  limit 1];
       
           // Check  if Capaign is associated with lead
           if(campaignMembList.size() > 0)
           {
                 if(!campaignMembList.get(0).Campaign.IsActive)
                 {
                        errorMsg = OORTelesalesTextConstant.IN_ACTIVE_CAMPAIGN_ERR_MSG;  
                        return;
                 }
               
                nextLeadId  =  campaignMembList.get(0).LeadId;
               
               leadList = [select TemporaryOwner__c,PreviewShow__c,OwnerId,PreviousOwner__c ,Preview_Clk_Display_Flag__c, LeadVisitedCounter__c from Lead where id = :nextLeadId];  // and TemporaryOwner__c=false and OORTelesalesCampaign__c=:campId    and  RecordTypeId=:localAdvertiserRecordTypeID ]; //and Lead_Status_ReadOnly__c='New'and Status='New' and RecordTypeId=:localAdvertiserRecordTypeID ];
               
               // Check if query has returned any row
               if(leadList.size() > 0 )
               {  
                    leadObj = leadList.get(0);
                    leadObj .TemporaryOwner__c = true;
                    leadObj.Preview_Clk_Display_Flag__c= true;
                    leadObj .OwnerId=UserInfo.getUserId();
                    leadObj.PreviewShow__c=True;
                    leadObj .PreviousOwner__c=UserInfo.getUserId();
                    //leadObj .LeadVisitedCounter__c =  leadObj .LeadVisitedCounter__c == null ? 0 : leadObj .LeadVisitedCounter__c +1;  
                    update leadList;

               } 
               else
               {
                  errorMsg = OORTelesalesTextConstant.NO_LEAD_FOR_CAMPAIGN_ERR_MSG ;  
               }
               
           }
           else
           {
              errorMsg = OORTelesalesTextConstant.NO_LEAD_FOR_CAMPAIGN_ERR_MSG ;  
           }
       }
       catch(Exception  e)
       {
             GeneralConstants.mailAnyExceptionToMe('OORTelesalesGetFirstLead','fetchLead',e);
       }   
   }
}